import adminApi from '@/api/admin'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    id: '',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_ID: (state, id) => {
    state.id = id
  }
}

const actions = {
  // 用户登录
  login({ commit }, adminInfo) {
    const { username, password } = adminInfo
    return new Promise((resolve, reject) => {
      adminApi.Login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.data.token)
        setToken(response.data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 根据 Token获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      adminApi.GetInfo(state.token).then(response => {
        const { item } = response.data
        console.log('@item', response.data)
        const { id, username } = item
        commit('SET_USERNAME', username)
        commit('SET_ID', id)
        resolve(item)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 注销登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      adminApi.Logout(state.token).then(() => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

